package com.qingxin.sys.filter;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.util.ParameterMap;
import org.apache.catalina.util.RequestUtil;

public class RequestEncodingPostWrapper extends RequestEncodingWrapper {

	/**
	 * 默认使用UTF-8
	 * 
	 * @param request
	 */
	public RequestEncodingPostWrapper(HttpServletRequest request) {
		super(request);
	}
	
	/**
	 * 指定编码
	 * 
	 * @param request
	 * @param encoding
	 */
	public RequestEncodingPostWrapper(HttpServletRequest request, String encoding) {
		super(request, encoding);
    }
	
	/**
	 * 获取编码的所有参数的不可变MAP对象<br>
	 * key : 参数名<br>
	 * value : 参数值数组<br>
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, String[]> getParameterMap() {
		String queryString = super.getQueryString();
		if(queryString == null || encoding==null){
			return getRequest().getParameterMap();
		}
		if(parameterMap!=null){
			return parameterMap;
		}
		Map<String, String[]> origMap = getRequest().getParameterMap();
		parameterMap = new ParameterMap<String, String[]>();
		if (origMap != null){
			parameterMap.putAll(origMap);
			byte[] bytes = null;
			try {
				bytes = queryString.getBytes(encoding);
				Map<String, String[]> map = new ParameterMap<String, String[]>();
				RequestUtil.parseParameters(map, bytes, encoding);
				
				Iterator it = map.keySet().iterator();
				while (it.hasNext()){
					String name = (String) it.next();
					String[] values = (String[]) map.get(name);
					String[] origValues = (String[]) parameterMap.get(name);
					if(values == null || origValues == null || origValues.length < values.length){
						continue;
					}
					System.arraycopy(values, 0, origValues, 0, values.length);
					
					parameterMap.put(getEncodedString(name), origValues);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			return origMap;
		}
		parameterMap.setLocked(true);
		return parameterMap;
	}
	

}
